package com.xysoft.support.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;

import com.xysoft.model.Action;
import com.xysoft.model.Role;
import com.xysoft.model.UserAction;
import com.xysoft.support.UserSecurityService;

public class UserSecurityServiceImpl extends BaseServiceImpl implements UserSecurityService {

	//@Cacheable(value = "USER_SECURITY_CACHE", key="#username")
	public User getLoginUserInfo(String username) {
		com.xysoft.model.User user = (com.xysoft.model.User)this.getBaseDao().findUniqueByProperty(
				com.xysoft.model.User.class, "username", username);
		if (user == null) {
			return null;
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);  
        User userdetail = new User(
        		username, user.getPassword(), user.isEnabled(), true, true, true, grantedAuths);
		return userdetail;
	}
	
	/**
	 * 取得用户的权限.  
	 */
    private Set<GrantedAuthority> obtionGrantedAuthorities(com.xysoft.model.User user) {  
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
        Set<Role> roles = user.getRoles();  
        for (Role role : roles) {
        	Set<Action> actions = role.getActions();
        	for (Action action : actions) {
        		authSet.add(new GrantedAuthorityImpl(action.getCode()));
        	}
        }
        Set<UserAction> uas = user.getUserActions();
        for (UserAction ua : uas) {
        	GrantedAuthority gay = new GrantedAuthorityImpl(ua.getAction().getCode());
        	if (authSet.contains(gay)) {
        		if (!ua.isEnabled()) authSet.remove(gay);
        	} else {
        		if (ua.isEnabled()) authSet.add(gay);
        	}
        }
        return authSet;  
    }

}
